import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ApiService } from 'src/app/core/api';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { RegionNumber } from 'src/app/model';
import { I18nService } from 'src/app/core/i18n/i18n.service';
import { NzMessageService } from 'ng-zorro-antd';
import { timer } from 'rxjs';

@Component({
  selector: 'app-pay-login',
  templateUrl: './pay-login.component.html',
  styleUrls: ['./pay-login.component.scss']
})
export class PayComponent implements OnInit {
  id:string;
  pageData:any = {
    data:{
      shopLogo:'../../../../assets/img/success.png'
    }
  };
  shopLogo:string = '../../../../assets/img/success.png';
  
  validateForm:FormGroup;
  getTimer:string;
  fromTime:number;
  isTimerOut:boolean = false;
  isClose:boolean = false;
  isEmail:boolean = true;
  isPayQR:boolean = false;
  // http://139.196.218.92:8182/wap/pay
  

  ngOnInit() {
    this.id = this.route.snapshot.queryParams["id"];
    this.loderPage();
    this.initRegionNumbers();
  };

  lx(){
    setTimeout(() => {
      this.loderPage()
    }, 2000);
  }
  
  async loderPage(){
    this.pageData = await this.ajx('http://139.196.218.92:8182/wap/checkAndInfo',{payId:this.id});
    this.pageData.data.shopLogo ? this.shopLogo = this.pageData.data.shopLogo : null;
    if(this.pageData.status != 0){
      if(this.pageData.status == 2028){
        this.gotoPayClosePage();
      }else
      if(this.pageData.data.shopLogo != undefined){
        this.shopLogo = this.pageData.data.shopLogo;
        this.gotoTimeOutPage();
      }else{
        this.gotoTimeOutPage();
      };
    }else{
      this.lx();
      this.fromTime = this.pageData.data.seconds * 1;
      this.resetTime(this.fromTime);
    };
  };
  async toPay(data){
    let tag:any={data:{message:''}};
    tag = await this.ajx('http://139.196.218.92:8182/wap/pay',data);
    if(tag.status != 0){
      this.message.create('error', tag.message);
    } else{
      this.gotoPayClosePage();
    };
  };
  
  ajx(url,data){
    let success = this.api.post( url, data).toPromise().catch(err => this.gotoTimeOutPage());
    return success
  };
  countdown():string{
    this.fromTime -= 1; 
    let a = this.fromTime / 60 +'';
    let f = parseInt(a);
    let m = this.fromTime % 60;

    return f + '分' + m + "秒";
  };
  resetTime(time: number) {
    let that = this;
    function countdown() {
      var s = time % 60
      var m = Math.floor((time / 60)) % 60
      var msg = `${(m < 10 ? '0' : '') + m}分钟${(s < 10 ? '0' : '') + s}秒`;
      that.getTimer = msg;
      if (--time > 0) {
        setTimeout(countdown, 1000)
      } else {
        that.gotoTimeOutPage();
        // 做结束的事
      }
    }
    countdown()
  };
  gotoTimeOutPage(){
    this.isTimerOut = true;
    this.isClose = true;
    this.isPayQR = false;
  };
  gotoPayClosePage(){
    this.isPayQR = false;
    this.isTimerOut = false;
    this.isClose = true;
  };
  towPayclose = false;
  gotoTwoPayClosePage(){
    this.towPayclose = true
    this.isTimerOut = true;
    this.isClose = true;
  };
  
  changeTab(isEmail:boolean){
    this.isEmail = isEmail;
    if(isEmail){
      this.validateForm = this.fb.group({
        fundPwd: [ null, [Validators.required ,  Validators.pattern('^[0-9]{6}$')] ],
        mail: [ null, [ Validators.required, Validators.pattern(/^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/)] ],
        phone: [ null, [ ] ],
        phoneNumberPrefix: [ '86' ],
      });
    }else{
      this.validateForm = this.fb.group({
        fundPwd: [ null, [ Validators.required ,  Validators.pattern('^[0-9]{6}$') ] ],
        mail: [ null, [] ],
        phone: [ null, [ Validators.required ] ],
        phoneNumberPrefix: [ '86' ],
      });
    };
  };

  regionNumbers: RegionNumber[] = [];
  private initRegionNumbers() {
    this.i18nService.getRegionNumbers().subscribe(res => {
      if (res.status === 0) {
        this.regionNumbers = res.data;
      }else {
        this.message.create('error', res.message);
      };
      if (!this.regionNumbers || this.regionNumbers.length === 0) {
        this.message.create('warning', 'region numbers is empty');
      } else {
        // this.seletedRegionNumber = '' + this.regionNumbers[0].number;
        // this.phoneForm.patchValue({ regionNumber: '' + this.regionNumbers[0].number});
      }
    }, error => this.message.create('error', JSON.stringify(error)));
  };

  handleOk(from:any):void{
    let data ={
      loginId:'',
      fundPwd:'',
      payId: this.id,
    };
    if(this.isEmail){
      data.fundPwd = from.fundPwd;
      data.loginId = from.mail;
    }else{
      data.fundPwd = from.fundPwd;
      data.loginId = from.phoneNumberPrefix + '-' + from.phone;
    };
    this.toPay(data);

  };
  phoneNumberPrefix:string;
  constructor(
    private api: ApiService,
    private route: ActivatedRoute,
    private fb: FormBuilder,
    private i18nService: I18nService,
    private message: NzMessageService,
    
  ) {
    this.validateForm = this.fb.group({
      fundPwd: [ null, [ Validators.required ,  Validators.pattern('^[0-9]{6}$') ] ],
      mail: [ null, [ Validators.required, Validators.pattern(/^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/)] ],
      phone: [ null, [ ] ],
      phoneNumberPrefix: [ '86' ],
      
    });
   };
};
